import React, { PureComponent, Fragment } from 'react';
import moment from 'moment';
import { connect } from 'dva';
import {
  Button,
  Tag,
  Modal,
  Form,
  message,
  Table,
  Radio,
  Input,
  Icon,
  Drawer,
  Row,
  Tree,
  Switch,
  Progress, DatePicker, Badge, Select,Col
} from 'antd';
import MyPagination from '@/components/MyPagination';
import find from 'lodash/find';
import sortBy from 'lodash/sortBy';
import Loading from '@/components/Loading';
import debounce from 'lodash/debounce';
import Detail from './../Meters/Detail';
import ReactDataGrid from 'react-data-grid';
import ReactEcharts from 'echarts-for-react';
import { renderValveOpen } from '@/utils/utils';
import forEach from 'lodash/forEach';
import request from '@/utils/request';

const { TreeNode, DirectoryTree } = Tree;
const FormItem = Form.Item;
const { confirm } = Modal;
const Option = Select.Option;
const ButtonGroup = Button.Group;

const RadioButton = Radio.Button;

const RadioGroup = Radio.Group;

@connect(({ DMA_Statistics, loading, global }) => ({
  DMA_Statistics,
  global,
  loading: loading.models.DMA_Statistics,
}))
@Form.create()
class BasicList extends PureComponent {
  constructor(props) {
    super(props);
    this.permissions = JSON.parse(sessionStorage.getItem('permissions'));
    this.state = {
      showAddBtn: find(this.permissions, { name: 'device_add_and_edit' }),
      showdelBtn: find(this.permissions, { name: 'device_delete' }),
      showPasswordBtn: find(this.permissions, { name: 'user_default_password_edit' }),
      user_password_reset: find(this.permissions, { name: 'user_password_reset' }),
      visible: false,
      done: false,
      page: 1,
      per_page: 30,
      username: '',
      editRecord: {},
      selectedRowKeys: [],
      all_vendors: [],
      tableY:'calc(100vh - 380)'
    };
  }


  componentDidMount() {

    const that = this;
    const { dispatch } = this.props;
    const {
      DMA_Statistics: { pageLoaded, scrollData },
    } = this.props;
    console.log('pageLoaded', pageLoaded);
    if (pageLoaded) {
      setTimeout(() => {
        setTimeout(function(){
          dispatch({
            type: 'DMA_Statistics/changeTableY',
          });
        },0)
      }, 0);

    } else {
      const {
        DMA_Statistics: { searchParams },
      } = this.props;
      console.log('searchParams', searchParams);
      dispatch({
        type: 'DMA_Statistics/fetch',
        payload: searchParams,
        callback: () => {
          const { dispatch } = this.props;
          dispatch({
            type: 'DMA_Statistics/changeLoaded',
          });
          dispatch({
            type: 'DMA_Statistics/changeTableY',
          });

          const {
            DMA_Statistics: { data },
          } = this.props;
          console.log('data',data)
          if (data.length > 0) {
            that.props.dispatch({
              type: 'DMA_Statistics/changeSelectRow',
              payload: {
                selectedIndex: [0],
                row: data[0],
                searchParams:{
                  ...searchParams
                }
              },
              callback:()=>{
                setTimeout(function(){
                  that.changeTableY();
                },0)
                const {
                  DMA_Statistics: { pickRowData1 },
                } = this.props;
                if(pickRowData1.data.length>0){
                  that.props.dispatch({
                    type: 'DMA_Statistics/changeSelectRow2',
                    payload: {
                      selectedIndex: [0],
                      row: pickRowData1.data[0],
                    },
                    callback:()=>{
                    }
                  });
                }
              }
            });
          }




        },
      });
    }

    window.addEventListener('resize', this.resize);

  }

  scroll = (e) => {
    console.log('scroll');
    const { dispatch } = this.props;
    dispatch({
      type: 'DMA_Statistics/changeScroll',
      payload: {
        x: e.target.scrollLeft,
        y: e.target.scrollTop,
      },
    });
  };

  resize = () => {
    const { dispatch } = this.props;

    // this.changeTableY();
    dispatch({
      type: 'DMA_Statistics/changeTableY',
    });
  };

  changeTableY = () => {
    this.setState({
      tableY: document.body.offsetHeight -
        document.querySelector('.analysis').getBoundingClientRect().top - 50,
    });
  };

  componentWillUnmount() {
    console.log('componentWillUnmount');
    window.removeEventListener('resize', this.resize);
    return;
    const table = document.querySelector('.ant-table-body');
    table.removeEventListener('scroll', debounce(this.scroll, 300));
  }

  handleSearch = (values, cb) => {
    console.log('handleSearch', values);
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: 'DMA_Statistics/fetch',
      payload: {
        ...values,
      },
      callback() {
        console.log('handleSearch callback');
        if (cb) cb();
        const {
          DMA_Statistics: { scrollData },
        } = that.props;
        const table = document.querySelector('.react-grid-Canvas');
        if(table){
          setTimeout(() => {
            table.scrollTop = 0;
            table.scrollLeft = scrollData.x;
          }, 0);
        }
      },
    });
  };

  keyPress=(e)=>{
    let theEvent = e || window.event;
    let code = theEvent.keyCode || theEvent.which || theEvent.charCode;
    if (code === 13) {
      e.preventDefault();
      console.log('key press')
      const { form } = this.props;
      form.validateFields((err, fieldsValue) => {
        if (err) return;

        this.handleSearch({
          name:fieldsValue.name,
          number:fieldsValue.number,
        });

      });
    }
  }
  handleAdd = () => {
    const formValues = this.AddForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    const that = this;
    this.props.dispatch({
      type: 'DMA_Statistics/add',
      payload: {
        ...formValues,
      },
      callback() {
        message.success('新建设备成功');
        that.setState({
          addModal: false,
        });
        const {
          DMA_Statistics: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };

  handleFormReset = () => {
    const { form } = this.props;
    form.resetFields();
    this.handleSearch({
      date: moment().subtract(1, "day").format("YYYY-MM-DD"),
      meter_number: '',
      user_number: '',
      name: '',
      size_type:'',
      vendor_id: '',
      status: '0',
      page: 1,
      per_page: 50,
    });
  };

  getOption = () => {
    console.log('render getOption')
    const {
      DMA_Statistics: { pickRowData2,searchParams },
    } = this.props;
    const data = pickRowData2.items;
    console.log('getOption data',data)
    let Date = [];
    let Data = [];
    let diffData = [];
    let attrition_value=[]
    let growth_rate = [];
    forEach(data, (value, index) => {
      Date.push(value.date);
      Data.push({value:value.inflow_value, visualMap: false});
      diffData.push({value:value.outflow_value, visualMap: false})
      attrition_value.push({value:value.attrition_value, visualMap: false})

      growth_rate.push(parseFloat(value.attrition_rate));
    });
    let option = {
      // background: 'rgba(0,0,0,1)',
      color: ['#0083ff','#2ed500','#e86e3a'],
      animation: false,
      tooltip: {
        trigger: 'axis',
      },
      legend: {
        data: ['流入水量','流出水量','损耗水量','损耗率'],
      },
      toolbox: {
        show: true,
        feature: {
          dataView: {readOnly: true},
        },
      },
      xAxis: [
        {
          type: 'category',
          data: Date,
          axisPointer: {
            type: 'shadow',
          },
          splitArea: {
            show: true,
            interval: 0,
            areaStyle: {
              color: ['#f3f2f2', '#eceaea'],
            },
          },
        },
      ],
      yAxis: [
        {
          type: 'value',
          name: '水量(柱状图)',
          axisLabel: {
            formatter: '{value}(m3)',
          },
        },
        {
          type: 'value',
          name: '损耗率(折线图)',
          axisLabel: {
            formatter: '{value}(%)',
          },
          splitLine: {
            show: false,
          },
          max:100,
          min:0
        },
      ],
      grid: {
        top: '8%',
        left: '2%',
        right: '2%',
        bottom: '0%',
        containLabel: true,
      },
      dataZoom: [
        {
          type: 'slider',
          show: false,
          xAxisIndex: [0],
        },
        {
          type: 'inside',
          xAxisIndex: [0],
        },
      ],
      series: [
        {
          name: `流入水量`,
          type: 'bar',
          data: Data,
          barGap:0,//柱间距离
          barCategoryGap:'40%',
        },
        {
          name: '流出水量',
          type: 'bar',
          data: diffData,
          barGap:0,//柱间距离
          barCategoryGap:'40%',
        },
        {
          name: '损耗水量',
          type: 'bar',
          data: attrition_value,
          barGap:0,//柱间距离
          barCategoryGap:'40%',

        },
        {
          name: '损耗率',
          type: 'line',
          yAxisIndex: 1,
          symbolSize: 8,
          data: growth_rate,
          smooth: true,
          lineStyle: {
            normal: {
              width: 4,
            }
          },
          itemStyle: {
            normal: {
              color: '#d90000',
            },
          },
        },
      ],
    };
    return option;
  };

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
      DMA_Statistics: { searchParams,pickRowData ,selectedRowKeys},
    } = this.props;
    return (
      <Form layout="inline" className="search-form">
        <FormItem label={'间隔单位'}>
          {getFieldDecorator('interval_unit', {
            initialValue: searchParams.interval_unit
          })(
            <Radio.Group>
              <Radio.Button value="day">日粒度</Radio.Button>
              <Radio.Button value="month">月粒度</Radio.Button>
            </Radio.Group>
          )}
        </FormItem>
        <FormItem label={'开始日期'}>
          {getFieldDecorator('start_date', {
            initialValue: moment(searchParams.start_date),
          })(
            <DatePicker
              style={{width: '120px'}}
              allowClear={false}
              //disabledDate={disabledDate}
              format="YYYY-MM-DD"
            />
          )}
        </FormItem>
        <FormItem label={'结束日期'}>
          {getFieldDecorator('end_date', {
            initialValue: moment(searchParams.end_date),
          })(
            <DatePicker
              style={{width: '120px'}}
              allowClear={false}
              //disabledDate={disabledDate}
              format="YYYY-MM-DD"
            />
          )}
        </FormItem>
        <FormItem>
          <Button
            type="primary"
            icon='search'
            onClick={() => {
              const { form } = this.props;
              form.validateFields((err, fieldsValue) => {
                if (err) return;
                this.props.dispatch({
                  type: 'DMA_Statistics/fetch',
                  payload: {
                    interval_unit:fieldsValue.interval_unit,
                    start_date: moment(fieldsValue.start_date).format('YYYY-MM-DD'),
                    end_date: moment(fieldsValue.end_date).format('YYYY-MM-DD'),
                  },
                });
                this.props.dispatch({
                  type: 'DMA_Statistics/resetSelect',
                })

              });
            }}
          >
            查询
          </Button>
        </FormItem>
        <FormItem>
          <ButtonGroup>
            <Button type="primary" onClick={()=>{
              const {
                form,
                DMA_Statistics: { searchParams },
              } = this.props;
              this.props.dispatch({
                type: 'DMA_Statistics/fetch',
                payload: {
                  interval_unit:searchParams.interval_unit,
                  start_date: moment(searchParams.start_date).subtract(1,'month').format('YYYY-MM-DD'),
                  end_date:moment(searchParams.end_date).subtract(1,'month').format('YYYY-MM-DD'),

                },
                callback:()=>{
                  console.log('设置日期1')
                  form.setFieldsValue({
                    start_date:  moment(searchParams.start_date).subtract(1,'month'),
                    end_date:  moment(searchParams.end_date).subtract(1,'month'),
                  });
                }
              });
              this.props.dispatch({
                type: 'DMA_Statistics/resetSelect',
              })
            }}>
              <Icon type="left" />
              前一个月
            </Button>
            <Button type="primary"  onClick={()=>{
              const {
                form,
                DMA_Statistics: { searchParams },
              } = this.props;
              this.props.dispatch({
                type: 'DMA_Statistics/fetch',
                payload: {
                  interval_unit:searchParams.interval_unit,
                  start_date: moment(searchParams.start_date).add(1,'month').format('YYYY-MM-DD'),
                  end_date:moment(searchParams.end_date).add(1,'month').format('YYYY-MM-DD'),

                },
                callback:()=>{
                  console.log('设置日期2')
                  form.setFieldsValue({
                    start_date:  moment(searchParams.start_date).add(1,'month'),
                    end_date:  moment(searchParams.end_date).add(1,'month'),
                  });
                }
              });
              this.props.dispatch({
                type: 'DMA_Statistics/resetSelect',
              })
            }}>
              后一个月
              <Icon type="right" />
            </Button>
          </ButtonGroup>
        </FormItem>


      </Form>
    );
  }

  render() {
    const that = this;
    const {
      DMA_Statistics: { data, loading, tableY, pickRowData1, searchParams, selectedRowKeys, pickRowData2, total_consumption },
      global: { gridTableW },
    } = this.props;
    const defaultColumnProperties = {
      resizable: true,
    };
    const columns = [
      {
        name: '序号',
        width: 50,
        key: '_index',
        frozen: true,
        formatter: (event) => {
          const {
            DMA_Statistics: { meta },
          } = this.props;
          return <p className={'index'}>{ (event.value + 1)}</p>;
        },
      },
      {
        name: '类型',
        width: 70,
        key: 'source',
        formatter: (event) => {
          return <img  src={event.value} style={{width:'40px',height:'40px'}}/>;
        },
      },
      {
        name: '名称',
        width: 150,
        key: 'name',
      },
      {
        name: '操作',
        key: 'operate',
        width: 120,
        classname:'operate',
        formatter: (event,index) => {
          return  <Fragment>
            <Button
              type="primary"
              size="small"
              onClick={(e) => {
                this.props.dispatch({
                  type: 'DMA_Statistics/changeSelectRow2',
                  payload: {
                    selectedIndex: [index],
                    row: event.row,
                  },
                });
              }
              }
            >查看每天数据
            </Button>

          </Fragment>
        }
      }
    ].map(c => ({ ...defaultColumnProperties, ...c }));

    const RowRenderer = ({ renderBaseRow, ...props }) => {
      const className = props.row.status !== 1 ? 'table-error' : '';
      return <div className={className}>{renderBaseRow(props)}</div>;
    };
    const columnsAnt = [
      {
        title: '名称',
        dataIndex: 'name',
        key: 'name',
        width: '35%'
      },
      {
        title: '是否存在图关系',
        dataIndex: 'graph',
        key: 'graph',

        render: (val, record, index) => {
          return  <Fragment>
            {
              record.graph.edges.length>0?<p className="table-success table-status">存在</p>:<p className="table-error table-status">不存在</p>
            }
          </Fragment>
        }
      },
      {
        title: '操作',
        key: 'operate',
        width: '25%',
        classname:'operate',
        render: (val, record, index) => {
          return  <Fragment>
            <Button
              type="primary"
              size="small"
              onClick={(e) => {
                const that=this;
                that.props.dispatch({
                  type: 'DMA_Statistics/saveResetSelect2',
                  });

                that.props.dispatch({
                  type: 'DMA_Statistics/changeSelectRow',
                  payload: {
                    row:record,
                    searchParams:{
                      ...searchParams
                    }
                  },
                  callback:()=>{
                    setTimeout(function(){
                      // that.changeTableY();
                    },0)
                    const {
                      DMA_Statistics: { pickRowData1 },
                    } = this.props;
                    if(pickRowData1.data.length>0){
                      that.props.dispatch({
                        type: 'DMA_Statistics/changeSelectRow2',
                        payload: {
                          selectedIndex: [0],
                          row: pickRowData1.data[0],
                        },
                        callback:()=>{
                        }
                      });
                    }
                  }
                });
              }
              }
            >查看分区统计
            </Button>

          </Fragment>
        }
      }

    ]
    pickRowData1.data=sortBy(pickRowData1.data,['sort'])
    return <div className="custom-card">
      <div className="table-title"><span className={'title-item'}>水表漏损统计</span>
      </div>
      <div style={{padding:'16px'}}>
        <div  className="table-condition">{this.renderSimpleForm()}</div>
      </div>
      <div  style={{display:'flex',padding:'20px',background:'#f0f2f5'}}>
        <div  style={{width:'450px',background:'#fff',marginRight:'20px'}} >
          <div>
            <div  style={{width:'450px'}} className={'table-data-content'}>
              <h3 style={{marginLeft:'10px'}}>点击按钮选择DMA分区</h3>
              <Table
                className='meter-table ant-table-interval'
                rowKey={record => record.id}
                dataSource={data}
                columns={columnsAnt}
                scroll={{y: tableY}}
                bordered
                pagination={false}
                size="small"
              />
            </div>
          </div>
        </div>
        <div  style={{width:'400px',background:'#fff',marginRight:'20px'}} >
          <div>
            <div  style={{width:'400px'}} className={'table-data-content'}>
              <h2 style={{color:'#3398DB',marginBottom:'10px',marginLeft:'10px',fontWeight:'bold'}}>
                {pickRowData1.name?pickRowData1.name:pickRowData1.number}
              </h2>
              {pickRowData1.name&&
                <ReactDataGrid
                  columns={columns}
                  rowGetter={i => {
                    return { ...pickRowData1.data[i], _index: i };
                  }}
                  headerRowHeight={35}
                  rowHeight={50}
                  rowsCount={pickRowData1.data.length}
                  minHeight={tableY}
                  width={300}
                  rowKey={'key'}
                  rowSelection={{
                    showCheckbox: false,
                    enableShiftSelect: true,
                    selectBy: {
                      indexes: selectedRowKeys,
                    },
                  }}
                  onRowClick={
                    (index, row) => {
                      console.log('row', row);
                      if (!row) {
                        return;
                      }
                    }
                  }

                />
              }
            </div>
          </div>
        </div>
        <div  style={{flex:1,background:'#fff',padding:'10px'}}>
          <h2 style={{color:'#3398DB',marginBottom:'10px',fontWeight:'bold'}}>
            {pickRowData2.name?pickRowData2.name:pickRowData2.number}
          </h2>
          {
            pickRowData2.name&&
            <ReactEcharts
              option={this.getOption()}
              style={{ height: tableY, width: '100%' }}
              // theme='my_theme'
              //onChartReady={this.onChartReadyCallback}
              //onEvents={EventsDict}
            />
          }

          {
            loading && <Loading/>
          }
        </div>
      </div>

      <Drawer
        title={`${this.state.editRecord.number} 详情`}
        placement="right"
        closable={false}
        destroyOnClose
        onClose={() => {
          this.setState({
            infoModal: false,
            editRecord: {},
          });
        }}
        width={800}
        visible={this.state.infoModal}
      >
        <Detail id={this.state.editRecord.id}></Detail>
      </Drawer>
    </div>;
  }
}

export default BasicList;
